package com.coda.service.impl;

import com.coda.Constant.MessageConstant;
import com.coda.Constant.StatusConstant;
import com.coda.common.PageResult;
import com.coda.common.Result;
import com.coda.context.BaseContext;
import com.coda.dto.AssignRoleDto;
import com.coda.dto.PageDto;
import com.coda.entity.Role;
import com.coda.entity.User;
import com.coda.exception.BaseException;
import com.coda.mapper.RoleMapper;
import com.coda.mapper.UserMapper;
import com.coda.service.RoleService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;

    /**&
     * 查询所有用户角色列表
     * @return
     */
    @Override
    public List<Role> getRoleList() {
        List<Role> roleList = roleMapper.getRoleList();
        return roleList;
    }

    /**
     * 根据id查询用户角色
     * @param id
     * @return
     */
    @Override
    public List<Role> getRoleListByUserId(Long id) {

        List<Role> roleList = roleMapper.getRoleListByUserId(id);
        return roleList;
    }

    /**
     * 根据id添加用户角色
     * @param assignRoleDto
     */
    @Override
    @Transactional
    public void addUserRole(AssignRoleDto assignRoleDto) {

        //获取用户id
        Long userId = assignRoleDto.getUserId();
        //获取需要添加的角色列表
        List<String> roleCheckList = assignRoleDto.getRoleCheckList();

        //获取当前用户
        User userInfo = userMapper.getUserById(BaseContext.getCurrentId());
        //获取请求中要删除的用户
        User userById = userMapper.getUserById(userId);
        //当修改比自己级别更高的用户时，不能修改
        if (Integer.parseInt(userInfo.getUserType()) > Integer.parseInt(userById.getUserType())) {
            throw new BaseException(Result.CODE_ERR_BUSINESS, MessageConstant.NOT_SET_USER_ROLE);
        }

        //先根据id删除对应用户角色
        roleMapper.deleteUserRoleByUserId(userId);

        for (String roleName : roleCheckList) {
            //根据角色名查询角色信息
            Role role = roleMapper.getRoleByName(roleName);
            //添加用户角色
            roleMapper.addRoleUser(role.getRoleId(),userId);
        }
    }

    /**
     * 分页查询角色列表
     * @param role
     * @return
     */
    @Override
    public PageResult getRolePage(PageDto pageDto,Role role) {
        //设置分页参数
        PageHelper.startPage(pageDto.getPageNum(),pageDto.getPageSize());
        //分页查询
        Page<Role> page = roleMapper.getRolePage(role);

        PageResult pageResult = new PageResult(page.getTotal(), page.getResult());
        return pageResult;
    }

    /**
     * 添加角色
     * @param role
     */
    @Override
    public void addRole(Role role) {
        //设置属性
        role.setRoleState(StatusConstant.USER_STATE_NOT_PASS);
        roleMapper.addRole(role);
    }

    /**
     * 更改角色状态
     * @param role
     */
    //todo 后端更改状态逻辑完成，前端按钮展示问题
    @Override
    public void updateState(Role role) {
        //获取当前用户级别
        User user = userMapper.getUserById(BaseContext.getCurrentId());
        //如果级别不为1，则不能修改状态
        if (!(user.getUserState().equals(StatusConstant.USER_STATE_PASS))){
            throw new BaseException(Result.CODE_ERR_BUSINESS,MessageConstant.NOT_STATE_AUTH);
        }
        //如果角色有对应的用户，则不能修改状态
        int count = roleMapper.getRoleUserCount(role.getRoleId());
        if (count>0){
            throw new BaseException(Result.CODE_ERR_BUSINESS,MessageConstant.NOT_STOP);
        }

        roleMapper.update(role);
    }

    /**
     * 根据id删除角色
     * @param id
     */
    @Override
    public void deleteRoleById(Long id) {
        //只有级别为1的用户才能删除角色，否则不能删除
        User user = userMapper.getUserById(BaseContext.getCurrentId());
        if (!(user.getUserType().equals("1"))){
            throw new BaseException(Result.CODE_ERR_BUSINESS,MessageConstant.NOT_AUTH_DELETE);
        }
        //如果当前角色是启用状态不能删除
        Role role = roleMapper.getRoleById(id);
        if ((role.getRoleState().equals("1"))){
            throw new BaseException(Result.CODE_ERR_BUSINESS,MessageConstant.STOP_ROLE);

        }
        //如果角色有对应的用户，则不能删除
        int count = roleMapper.getRoleUserCount(id);
        if (count>0){
            throw new BaseException(Result.CODE_ERR_BUSINESS,MessageConstant.NOT_DELETE_ROLE);
        }
        roleMapper.deleteRoleById(id);
    }

    /**
     * 根据id修改角色
     * @param role
     */
    @Override
    public void updateRole(Role role) {
        //只有级别为1的用户才能修改角色，否则不能修改
        User user = userMapper.getUserById(BaseContext.getCurrentId());
        if (!(user.getUserType().equals("1"))){
            throw new BaseException(Result.CODE_ERR_BUSINESS,MessageConstant.NOT_AUTH_DELETE);
        }

        roleMapper.update(role);
    }
}
